package com.test;

import java.io.File;
import java.util.List;

import com.dalin.common.clazz.Clazz;
import com.dalin.common.clazz.Interfazz;
import com.dalin.common.utils.FileUtils;
import com.dalin.common.utils.StringUtils;
import com.dalin.common.utils.TextUtils;
import com.dalin.framework.dao.DbDao;
import com.dalin.platform.autocode.service.AutocodeService;
import com.dalin.platform.autocode.vo.BeanInfoVo;
import com.dalin.platform.etl.condition.EtlTableInfoCondition;
import com.dalin.platform.etl.model.EtlColumnInfoEntity;
import com.dalin.platform.etl.model.EtlTableInfoEntity;
import com.dalin.platform.etl.service.EtlService;
import com.dalin.platform.etl.vo.EtlTableInfoVo;
import com.dalin.platform.pub.PlatContext;

public class SyProjectAutoCode {
	public static void fuck() throws Exception {
		EtlService etlService = (EtlService) PlatContext.getBean("etlService");
		etlService.synDbInfoStructure(6L);
		EtlTableInfoCondition cond = new EtlTableInfoCondition();
		cond.setDatabaseId(6L);
		List<EtlTableInfoVo> tableList = etlService.queryEtlTableInfos(
				cond.prepareParams()).getDataList();
		for (EtlTableInfoVo enty : tableList) {
			autoCode(enty);
		}
	}

	public static void autoCode(EtlTableInfoVo enty) throws Exception {
		BeanInfoVo vo = new BeanInfoVo();
		vo.setTableId(enty.getTableId());
		//vo.setTableName(enty.getTableName());
		vo.setActionServiceInterfaceName("tempService");
		vo.setSavedPath("c:/autocode/" + enty.getTableName() + "/");
		vo
				.setJavaPackageName("com.dalin.projects.productionPermit.models.entity");
		vo
				.setAnnotationPackageName("com.dalin.projects.productionPermit.models.entity");
		vo.setConditionPackageName("com.dalin.projects.productionPermit");
		vo.setGridJspName(StringUtils.underlineToLowerCamelCase(enty
				.getTableName())
				+ "Manager.jsp");
		vo.setAddModJspName(StringUtils.underlineToLowerCamelCase(enty
				.getTableName())
				+ "AddMod.jsp");

		AutocodeService autocodeService = (AutocodeService) PlatContext
				.getBean("autocodeService");
		File f = new File(vo.getSavedPath());
		FileUtils.deleteFiles(f);
		f.mkdirs();

		// Annotation值对象
		Clazz annotationClazz = autocodeService.getAnnotationClazz(
				vo.getTableId(), vo.getAnnotationPackageName());
		overwriteTextFile(vo.getSavedPath(), annotationClazz);
		
		// VO值对象
		Clazz myClazz = autocodeService.getJavaClazz(vo.getTableId(), vo
				.getJavaPackageName());
		overwriteTextFile(vo.getSavedPath(), myClazz);

		// entity值对象
		String s = createSqlMap(enty);
		TextUtils.overwriteToText(s, new File(vo.getSavedPath()
				+ StringUtils.underlineToUpperCamelCase(enty.getTableName())
				+ "Entity.xml"));

		// Condition查询条件对象
		myClazz = autocodeService.getConditionClazz(vo.getTableId(), vo
				.getConditionPackageName());
		overwriteTextFile(vo.getSavedPath(), myClazz);

		// service接口类
		Interfazz fazz = autocodeService.getServiceInterfaceClazz(vo
				.getTableId(), vo.getServiceInterfacePackageName());
		TextUtils.overwriteToText(fazz.toString(), new File(vo.getSavedPath()
				+ fazz.getInterfaceName() + ".java"));

		// service接口实现类
		Clazz serviceImpleClazz = autocodeService.getServiceImpleClazz(vo
				.getTableId(), vo.getServiceInterfacePackageName() + ".imple");
		overwriteTextFile(vo.getSavedPath(), serviceImpleClazz);

		// 增加修改action类
		Clazz addModActionClazz = autocodeService.getAddModActionClazz(vo
				.getActionServiceInterfaceName(), vo.getTableId(), vo
				.getActionPackageName());
		overwriteTextFile(vo.getSavedPath(), addModActionClazz);

		// 删除功能action类
		Clazz delActionClazz = autocodeService.getDelActionClazz(vo
				.getActionServiceInterfaceName(), vo.getTableId(), vo
				.getActionPackageName());
		overwriteTextFile(vo.getSavedPath(), delActionClazz);

		// 查找操作的action类
		Clazz findActionClazz = autocodeService.getFindActionClazz(vo
				.getActionServiceInterfaceName(), vo.getTableId(), vo
				.getActionPackageName());
		overwriteTextFile(vo.getSavedPath(), findActionClazz);

		// 查询列表操作的action类
		Clazz queryActionClazz = autocodeService.getQueryActionClazz(vo
				.getActionServiceInterfaceName(), vo.getTableId(), vo
				.getActionPackageName());
		overwriteTextFile(vo.getSavedPath(), queryActionClazz);

		// jsp列表页面
		String gridJspContentStr = autocodeService.getGridJspContent(vo
				.getTableId());
		TextUtils.overwriteToText(gridJspContentStr, new File(vo.getSavedPath()
				+ vo.getGridJspName()));

		// jsp添加修改页面
		String addModJspContentStr = autocodeService.getAddModJspContent(vo
				.getTableId());
		TextUtils.overwriteToText(addModJspContentStr, new File(vo
				.getSavedPath()
				+ vo.getAddModJspName()));
		annotationClazz = autocodeService.getAnnotationClazz(vo
				.getTableId(), "");
		// 其他配置文件
		StringBuffer otherConfig = new StringBuffer();
		otherConfig.append("<sqlMap resource=\"").append(
				vo.getAnnotationPackageName() + "/").append(
				annotationClazz.getClassName()).append("\" />\n\n");
		otherConfig.append("<bean id=\"").append(
				vo.getActionServiceInterfaceName()).append(
				"\" parent=\"txProxyTemplate\">\n");
		otherConfig.append("	<property name=\"target\">\n");
		otherConfig.append("		<bean class=\"").append(
				vo.getServiceInterfacePackageName()).append(".imple.").append(
				serviceImpleClazz.getClassName()).append(
				"\" autowire=\"byName\" />\n");
		otherConfig.append("	</property>\n");
		otherConfig.append("</bean>\n\n");

		otherConfig.append("<bean id=\"").append(
				addModActionClazz.getClassName()).append("\" class=\"").append(
				vo.getActionPackageName() + ".").append(
				addModActionClazz.getClassName()).append(
				"\" scope=\"prototype\" autowire=\"byName\" />\n");
		otherConfig.append("<bean id=\"").append(delActionClazz.getClassName())
				.append("\" class=\"").append(vo.getActionPackageName() + ".")
				.append(delActionClazz.getClassName()).append(
						"\" scope=\"prototype\" autowire=\"byName\" />\n");
		otherConfig.append("<bean id=\"")
				.append(findActionClazz.getClassName()).append("\" class=\"")
				.append(vo.getActionPackageName() + ".").append(
						findActionClazz.getClassName()).append(
						"\" scope=\"prototype\" autowire=\"byName\" />\n");
		otherConfig.append("<bean id=\"").append(
				queryActionClazz.getClassName()).append("\" class=\"").append(
				vo.getActionPackageName() + ".").append(
				queryActionClazz.getClassName()).append(
				"\" scope=\"prototype\" autowire=\"byName\" />\n\n");

		otherConfig.append("<action name=\"").append(
				getReqActionUrl(addModActionClazz.getClassName())).append(
				"\" class=\"").append(addModActionClazz.getClassName()).append(
				"\" />\n");
		otherConfig.append("<action name=\"").append(
				getReqActionUrl(delActionClazz.getClassName())).append(
				"\" class=\"").append(delActionClazz.getClassName()).append(
				"\" />\n");
		otherConfig.append("<action name=\"").append(
				getReqActionUrl(findActionClazz.getClassName())).append(
				"\" class=\"").append(findActionClazz.getClassName()).append(
				"\" />\n");
		otherConfig.append("<action name=\"").append(
				getReqActionUrl(queryActionClazz.getClassName())).append(
				"\" class=\"").append(queryActionClazz.getClassName()).append(
				"\" />\n");
		TextUtils.overwriteToText(otherConfig.toString(), new File(vo
				.getSavedPath()
				+ "otherConfig.xml"));
	}

	private static void overwriteTextFile(String savedPath, Clazz myClazz)
			throws Exception {
		TextUtils.overwriteToText(myClazz.toString(), new File(savedPath
				+ myClazz.getClassName() + ".java"));
	}

	private static String getReqActionUrl(String actionClassName)
			throws Exception {
		actionClassName = actionClassName.substring(0,
				actionClassName.length() - 6);
		return actionClassName.substring(0, 1).toLowerCase()
				+ actionClassName.substring(1);
	}

	private static String createSqlMap(EtlTableInfoVo vo) throws Exception {
		DbDao dao = (DbDao) PlatContext.getBean("dao");
		EtlTableInfoEntity tableEnty = (EtlTableInfoEntity) dao.findObjById(
				EtlTableInfoEntity.class, vo.getTableId());
		List<EtlColumnInfoEntity> proList = tableEnty.getEtlColumnInfoEntitys();

		StringBuffer sb = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		sb
				.append("<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\">\n");
		sb.append("<sqlMap namespace=\""
				+ StringUtils.underlineToUpperCamelCase(vo.getTableName())
				+ "Entity" + "\">\n");
		sb.append("<typeAlias alias=\""+StringUtils.underlineToUpperCamelCase(vo.getTableName())+"\" type=\"com.dalin.projects.productionPermit.models.entity."
						+ StringUtils.underlineToUpperCamelCase(vo
								.getTableName()) + "Entity\" />\n\n");
		sb.append("<select id=\"selectList\" parameterClass=\"com.dalin.projects.productionPermit.glb.vos."
						+ StringUtils.underlineToUpperCamelCase(vo
								.getTableName())
						+ "Condition\" resultClass=\""+StringUtils.underlineToUpperCamelCase(vo.getTableName())+"\">\n");
		sb.append("    select\n");
		int i = 0;
		for (EtlColumnInfoEntity enty : proList) {
			i++;
			sb.append("        t."
					+ enty.getColumnName()
					+ " as "
					+ StringUtils.underlineToLowerCamelCase(enty
							.getColumnName()));
			if (i == proList.size()) {
				sb.append(" \n");
			} else {
				sb.append(", \n");
			}
		}
		sb.append("    from " + vo.getTableName() + " t where 1=1\n");
		for (EtlColumnInfoEntity enty : proList) {
			sb.append("    <isNotEmpty prepend=\" and \" property=\""
					+ StringUtils.underlineToLowerCamelCase(enty
							.getColumnName())
					+ "\"><![CDATA[ t."
					+ enty.getColumnName()
					+ " = #"
					+ StringUtils.underlineToLowerCamelCase(enty
							.getColumnName()) + "#]]></isNotEmpty>\n");
		}
		sb.append("</select>\n\n");
		
		sb.append("<select id=\"findById\" parameterClass=\"java.lang.Long\" resultClass=\""+StringUtils.underlineToUpperCamelCase(vo.getTableName())+"\">\n");
		sb.append("<![CDATA[\n");
		sb.append("    select\n");
		int ii = 0;
		for (EtlColumnInfoEntity enty : proList) {
			ii++;
			sb.append("        t."
					+ enty.getColumnName()
					+ " as "
					+ StringUtils.underlineToLowerCamelCase(enty
							.getColumnName()));
			if (ii == proList.size()) {
				sb.append(" \n");
			} else {
				sb.append(", \n");
			}
		}
		sb.append("    from " + vo.getTableName() + " t where t.主键 =#主键属性#\n");
		sb.append("]]>\n");
		sb.append("</select>\n\n");
		
		sb.append("<delete id=\"delete\" parameterClass=\"java.lang.Long\">\n");
		sb.append("<![CDATA[\n");
		sb.append("    delete from " + vo.getTableName() + " t where t.主键=#主键属性#\n");
		sb.append("]]>\n");
		sb.append("</delete>\n\n");
		
		sb.append("<insert id=\"insert\" parameterClass=\"com.dalin.projects.productionPermit.models.entity."
				+ StringUtils.underlineToUpperCamelCase(vo.getTableName()) + "Entity\">\n");
  		sb.append("    <selectKey keyProperty=\"主键属性\" resultClass=\"java.lang.Long\">\n");
  		sb.append("        SELECT SEQ_" + vo.getTableName() + ".NEXTVAL FROM DUAL\n");
  		sb.append("    </selectKey>\n");
  		sb.append("    insert into " +vo.getTableName() +"(\n");
  		for (int j = 0; j < proList.size(); j++) {
  			EtlColumnInfoEntity enty = proList.get(j);
			sb.append("        "+ enty.getColumnName());
			if (j == proList.size() - 1) {
				sb.append(" \n");
			} else {
				sb.append(", \n");
			}
		}
  		sb.append("    ) values (\n");
  		for (int j = 0; j < proList.size(); j++) {
  			EtlColumnInfoEntity enty = proList.get(j);
			sb.append("        #"+ StringUtils.underlineToLowerCamelCase(enty
					.getColumnName())+"#");
			if (j == proList.size() - 1) {
				sb.append(" \n");
			} else {
				sb.append(", \n");
			}
		}
  		sb.append("    )\n");
		sb.append("</insert>\n\n");
		
		
		// modify
		sb.append("<update id=\"update\" parameterClass=\"com.dalin.projects.productionPermit.models.entity."
				+ StringUtils.underlineToUpperCamelCase(vo.getTableName()) + "Entity\">").append("\n");
		sb.append("<![CDATA[\n");
		sb.append("    update " + vo.getTableName() + " t set\n");
		for (int j = 0; j < proList.size(); j++) {
  			EtlColumnInfoEntity enty = proList.get(j);
			sb.append("        t."+enty.getColumnName() + "=#"+ StringUtils.underlineToLowerCamelCase(enty
					.getColumnName())+"#");
			if (j == proList.size() - 1) {
				sb.append(" \n");
			} else {
				sb.append(", \n");
			}
		}
		sb.append("    where t.主键 =#主键属性#\n");
		sb.append("]]>\n");
		sb.append("</update>\n\n");
		sb.append("</sqlMap>");
		return sb.toString();
	}
}
